<template>
  <div class="upload">
    <a-upload class="avatar-uploader" v-model:file-list="fileList" :accept="props.accept" :directory="props.directory"
      :listType="props.listType" :maxCount="props.maxCount" :multiple="props.multiple" :progress="progress"
      :isLimit="props.isLimit" @preview="handlePreview" :before-upload="beforeUpload"
      v-show="fileList.length < props.maxCount" :custom-request="(file: otherType) => handleUpload(file)"
      :show-upload-list="true">
      <div v-if="props.listType == 'text'">
        <a-button class="upload_button_line" :disabled="fileList.length >= props.maxCount"
          v-if="props.listType == 'text'">
          <upload-outlined></upload-outlined>
          {{ props.title }}
        </a-button>
        <div class="tips" v-if="props.accept">支持{{ props.accept }}格式</div>
      </div>

      <div v-show="props.listType == 'picture-card'">
        <plus-outlined />
        <span class="iconfont icon-Add"></span>
        <div class="ant-upload-text">{{ props.title }}</div>
      </div>
    </a-upload>

    <div class="uploadList" v-if="fileList.length && props.listType == 'picture-card'">
      <video class="imgList" :src="fileList[0].url" :style="styles" />
      <a-progress :percent="pp" size="small" v-if="pp !== 0 && pp !== 100" />
      <div class="uploadList-mask">
        <a-tooltip>
          <template #title>视频预览</template>
          <span class="iconfont icon-preview" @click="handlePreview(fileList[0])"></span>
        </a-tooltip>
        <a-tooltip>
          <template #title>视频删除</template>
          <span class="iconfont" @click="removePictrues(fileList[0])">&#xe8e2;</span>
        </a-tooltip>
      </div>
    </div>
    <base-modal :width="modAlProps.width" :isVisible="previewVisible" :title="previewTitle" :isCancleBtn="false"
      :buttons="buttons" @handleCancle="previewVisible = false" class="upload_modal">
      <template v-slot:body>
        <!-- <img alt="previewImage" :style="styles" :src="previewImage" />
         -->
        <video alt="example" style="width: 100%" :src="previewImage" controls></video>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import { message } from "ant-design-vue";
import { baseUploadProps } from "./uploadConfig/props";
import { dataSourceType } from "../../type";
import { request } from "@/api/axios";
//import request from "@/api/index";
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
//props
const props = defineProps(baseUploadProps);
//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
]);
//type
type otherType = {
  [propName: string]: any;
};
//data
const previewVisible = ref<Boolean>(false);
const previewImage = ref<string>("");
const previewTitle = ref<string>("");
const fileList = ref<dataSourceType[]>([]);
let acceptTypeList = ref<string[]>([]);
let styles = ref<string>("");
//模态框
const modAlProps = reactive({
  width: "M",
  title: "",
});
const progress = reactive({
  // 重写进度条
  strokeColor: {
    "0%": "#1890FF",
    "100%": "#1890FF",
  },
  strokeWidth: 2,
  format: (percent = 0) => {
    return `${parseFloat((+percent).toFixed(0))}%`;
  },
  class: "test",
  style: { width: "95%", fontSize: "12px" },
});
const pp = ref<string | number>(0);
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//watch
watch(
  () => props.fileList,
  (newVal, oldVal) => {
    if (newVal.length) {
      fileList.value = newVal;
      nextTick(() => {
        getImageStyle(newVal[0].url);
      })

    } else {
      fileList.value = [];
    }
  },
  { deep: true, immediate: true }
);
//methods
const getImageStyle = (src: string) => {
  const url = src;
  if (url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      if (img.naturalWidth >= img.naturalHeight) {
        styles.value = `width:100%;height:auto`;
      } else {
        styles.value = `width:auto;height:100%`;
      }
    };
  }
};
//// 删除图片
const removePictrues = (info: any) => {
  //
  emit("upload_remove_Finished", info);
};
const beforeUpload = (file: otherType["fileList"][number]) => {
  // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
  return new Promise((resolve, reject) => {
    // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
    const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
    let isFileType = true;
    if (acceptTypeList.value.length) {
      isFileType = acceptTypeList.value.includes(backgFix);

      if (!isFileType) {
        message.error(`只能上传${acceptTypeList.value.join(",")}格式文件!`);
        return false;
      }
    }

    let isLt2M = true;
    if (props.isLimit) {
      isLt2M =
        props.isLimit == 0 ? true : file.size / 1024 / 1024 < props.isLimit;
      if (!isLt2M) {
        message.error(`文件大小不得超过 ${props.isLimit} MB!`);
        return false;
      }
    }

    if (isFileType && isLt2M) {
      //fileList.value = [...fileList.value, file]
      return resolve(true);
    }
  });
};

const handleUpload = (options: otherType) => {
  // 上传到服务器

  const param = new FormData(); // 创建form对象
  param.append("files", options.file, options.file.name); // 通过append向form对象添加数据
  //
  // param.append("toConvertPdf", "1");
  if (props.isAutoUpload) {
    // props.isAutoUpload 用来判断是否能直接上传，若不能，需要用emit传递出formData数据到调取处

    options.file.status = "success";
    //  request.fetchsiteManageGetSiteDetail_upload(param,
    //  	{
    //  	onUploadProgress: ({ total, loaded }) => {
    //        options.onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, options);
    //    },
    //  }
    //
    //  ).then((res: otherType) => { //直接调接口222
    //    if (res.code === '00000 00000') {
    ////    	options.onProgress({percent:100})
    ////    	progress.format(100)
    ////    	options.file.status = 'success';
    ////
    //  	 options.onSuccess(res.data, options.file);
    //    	setTimeout(()=>{
    //    		//fileList.value.push(options.file);
    //
    //        emit('uploadFinished', res.data);
    //    	}, 10000)
    //
    //    }
    //  })
    // 要放在global
    let headers: Record<string, any> = {
      "Content-Type":
        "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
      noWatermark: 1,
    };

    if (props.noWatermark != 1) {
      delete headers.noWatermark;
    }
    request
      .post("/server-admin/res/upload", param, {
        headers: headers,

        onUploadProgress: ({ total, loaded }) => {
          if (total) {
            pp.value =
              Math.round((loaded / total) * 100) < 100
                ? Math.round((loaded / total) * 100).toFixed(1)
                : (100 - Math.random() * 10).toFixed(1);
            if (options.onProgress) {
              //留足大图片渲染时间
              options.onProgress(
                { percent: Math.round((loaded / total) * 100).toFixed(2) },
                options
              );
            }
          }
        },
      })
      .then((res: any) => {
        if (res.data.code == "00000 00000") {
          emit("uploadFinished", res.data.data);
          pp.value = 100;
          if (options.onSuccess) {
            options.onSuccess(res.data.data, options);
          }
          message.success(res.data.message);
        } else {
          message.error(res.data.message);
          if (options.onError) {
            options.onError(res.data.data, options);
          }
          fileList.value = [];
        }
      })
      .catch((err) => {
        console.log(err, 9999);
      });
  } else {
    emit("uploadChangeFinished", options);
  }
};

const handlePreview = async (file: otherType["fileList"][number]) => {
  // 文件预览
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
    file.oriFileName || file.name || file.file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};

// const handleOk = () => {
// };
// computed
acceptTypeList = computed({
  get() {
    return props.accept ? props.accept.split(",") : [];
  },
  set() { },
});
</script>
<style lang="scss" scoped>
.upload_button_line {
  margin-bottom: 4px;
}

.tips {
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

.iconfont.icon-Add {
  font-size: 24px;
  color: rgba(0, 0, 0, 0.85);
}

.upload {
  .uploadList {
    width: 104px;
    height: 104px;
    margin-right: 8px;
    margin-bottom: 8px;
    text-align: center;
    vertical-align: top;
    background-color: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
    transition: border-color 0.3s;
    position: relative;
    padding: 8px;
    display: flex;
    align-items: center;

    .imgList {
      max-width: 88px;
      max-height: 100px;
    }

    .uploadList-mask {
      background-color: rgba(0, 0, 0, 0.5);
      width: 88px;
      height: 88px;
      margin: 8px;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      align-items: center;
      justify-content: center;
      display: none;

      .iconfont {
        width: 29px;
        color: rgba(255, 255, 255, 0.8);
      }

      .iconfont:hover {
        color: rgba(255, 255, 255, 1);
      }

      .icon-delete {
        margin-left: 0;
      }
    }
  }

  .uploadList:hover {
    .uploadList-mask {
      display: flex;
    }
  }
}
</style>
<style lang="scss">
.upload {
  .ant-progress-line {
    width: 78px;
    position: absolute;
    left: 12px;
    top: 43px;

    .ant-progress-bg {
      height: 2px !important;
    }
  }

  .ant-progress-status-success {
    display: none;
  }
}
</style>
